<?php

namespace falcon5\inc\Base;

use falcon5\inc\Helpers\UrlHelper;
use falcon5\inc\Exceptions\InvalidArgumentException;
use lucatume\DI52\ContainerException;

class LanguageAutoSwitch
{
    const AUTO_SWITCH = 'falcon5.autoSwitch';

    public function setAutoSwitch(string $autoSwitch)
    {
        update_option(LanguageAutoSwitch::AUTO_SWITCH, $autoSwitch);
    }

    public function getAutoSwitch()
    {
        return get_option(LanguageAutoSwitch::AUTO_SWITCH);
    }

    /**
     * @return bool
     * @throws ContainerException|InvalidArgumentException
     */
    public function checkAutoSwitch(): bool
    {
        /** @var WPOption $falcon5Option */
        $falcon5Option = falcon5_app(WPOption::class);
        /** @var LanguageAutoSwitch $falcon5AutoSwitch */
        $falcon5AutoSwitch = falcon5_app(LanguageAutoSwitch::class);
        $onlyHome     = apply_filters( 'falcon5_auto_redirect_only_home', false );
        $skipRedirect = apply_filters( 'falcon5_auto_redirect_skip', false );

        return ! $skipRedirect &&
            ! wp_doing_ajax() && // no ajax.
            ! falcon5_is_ajax() &&
            ! falcon5_wp_is_rest() &&
            ! falcon5_is_wp_admin() &&
            ! falcon5_check_proxy_useragent() &&
            $falcon5Option->getOriginalLanguage() !== UrlHelper::getCurrentLang() &&
            ( ! $onlyHome || ( UrlHelper::getPath() === '/' ) ) && // front_page.
            $falcon5AutoSwitch->getAutoSwitch() === 'on';
    }


    /**
     * 自动切换语言
     * @return void
     * @throws ContainerException|InvalidArgumentException
     */
    public function autoSwitch()
    {
        // 检查是否有浏览器语言信息
        if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
            return;
        }

        // 获取浏览器语言列表
        $browserLanguages = UrlHelper::getBrowserLanguages();
        if (empty($browserLanguages)) {
            return;
        }

        /** @var WPOption $falcon5Option */
        $falcon5Option = falcon5_app(WPOption::class);
        $originalLang = $falcon5Option->getOriginalLanguage();
        $allowedLanguages = $falcon5Option->getAllowedLanguages();

        // 获取当前语言信息
        $currentLang = UrlHelper::getCurrentLang() ? UrlHelper::getCurrentLang() : $originalLang;

        // 如果当前已经是非原始语言，不进行跳转
        if ($currentLang !== $originalLang) {
            return;
        }

        // 查找最佳匹配语言
        $bestLang = UrlHelper::findBestLanguage($browserLanguages, $allowedLanguages);
        if (!$bestLang || $bestLang === $originalLang) {
            return;
        }

        // 获取当前路径和查询参数
        $path = UrlHelper::getPath();
        $query = UrlHelper::getQuery(true);

        // 根据URL模式生成重定向URL
        $redirectUrl = UrlHelper::generateRedirectUrl($bestLang, $path, $query);

        // 执行重定向
        header('Vary: Accept-Language');
        UrlHelper::redirect($redirectUrl);
    }


}